#梦飞openmv AI视觉例程
import sensor, image, time, os, tf, math, os, gc

sensor.reset()                         # Reset and initialize the sensor.
sensor.set_pixformat(sensor.GRAYSCALE)    # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA)      # Set frame size to QVGA (320x240)
sensor.set_windowing((160, 160))       # Set 240x240 window.
sensor.skip_frames(time=2000)          # Let the camera adjust.
#lcd.init() # Initialize the lcd screen.
net=None
labels=None
try:
    labels = [line.rstrip('\n') for line in open("labels.txt")] #加载模型及label
    net = tf.load("fire_uint8.tflite") #模型名称需要自己修改
except Exception as e:
    raise Exception('Failed to load "fire_uint8.tflite", did you copy the .tflite and labels.txt file onto the mass-storage device? (' + str(e) + ')')
print(labels) #打印label和模型信息是否正常
print(net)
clock = time.clock()
while(True):
    clock.tick()
    img = sensor.snapshot()
    #hist=img.get_histogram() #对于数字识别等场景需要将目标图像二值化处理，若直接是RGB识别的则不用处理
    #thread=hist.get_threshold()
    #img.binary([(0,thread[0])])
    for obj in tf.classify(net, img, min_scale=1.0, scale_mul=0.5, x_overlap=0.0, y_overlap=0.0):
        print(obj) #打印分类结果
        out = obj.output()
        max_idx = out.index(max(out)) #从分类结果中找到概率最大的，并展示在图像中
        score = int(out[max_idx]*100)
        if (score < 75): #这里概率阈值可以按实际结果修改
            score_str = "??:??%"
        else:
            score_str = "%s:%d%% "%(labels[max_idx], score)
            print(score_str)
        img.draw_string(0, 0, score_str, color=(255, 0, 0))
    #lcd.display(img)
    print(clock.fps(), "fps", end="\n\n")
    gc.collect()
